import { game, ui, _status, ai, lib, get } from "../../../../noname.js";
import { swTool } from "../../main/swTool.js";
import { MAIN } from "./config/main.js";
export const type = "mode";
/**
 * @type { () => importModeConfig }
 */
export const hemengaozhan = {
	name: "hemengaozhan",
	startBefore: function () {
		_status.extensionMode = hemengaozhan
	},
	reinit: function (...args) {
		const [characters, info, skins, playersBag, playersInfo] = args;
		_status.sw_playersBag = playersBag;
		_status.sw_playersInfo = playersInfo;
		_status.gameInfomation = info;
		lib.characterSubstitute = skins;

		for (const c in characters) {
			const { name, character, info } = characters[c]
			lib.character[character] = info
			if (name) {
				lib.translate[character] = name
			}
		}
		game.layoutGame();
	},
	oninit: function() {
		swTool.addGroup('lonely','望','守望',{ color:'#6652ff'})
		swTool.addGroup('blood','血','血庭教会',{ color:'#9a1111'})
		swTool.addGroup('aili','莉','九条艾莉',{ color:'#bf2bc4'})
		swTool.addGroup('chest','箱','箱子',{ color:'#ffdd00'})

		swTool.addNature(
			'sw_shui',
			'水',
			{ linked: true, order: 50, lineColor: [0, 161, 233], color: '#00A1E9' },
			"rgba(40,243,223,1)",
			)
		swTool.addNature(
			'sw_xue',
			'血',
			{ linked: false, order: 60, lineColor: [154, 17, 17], color: '#9a1111' },
			"rgba(154,17,17,1)",
			"出牌阶段，对你攻击范围内的一名角色使用。其须使用一张【闪】，否则你对其造成1点血属性伤害。若你造成血属性伤害且你的势力为“血庭教会”，你可以选择对自己造成1点伤害，然后摸1张牌且本回合出杀次数+1。"
			)
	},
	start() {
		"step 0"
		if (!_status.connectMode) {
			alert('目前仅联机模式可玩');
			game.exit();
			event.finish();
		}
		//TODO:
		_status.mode = get.config("hemengaozhan_mode");
		event.replacePile = function () {
			var banCard = ["muniu", "lebu", "bingliang", "diaohulishan"]
			var newCard = []
			for (var i = 0; i < lib.card.list.length; i++) {
				const card = lib.card.list[i];
				var name = card[2];
				if (banCard.includes(name)) {
					lib.card.list.splice(i--, 1);
				}
				if (card?.[3] === "thunder") {
					const newCardEntry = [...card];
					newCardEntry[3] = "sw_shui";
					newCard.push(newCardEntry);
				}
				else if (card?.[3] === "fire" && card?.[0] === "heart") {
					const newCardEntry = [...card];
					newCardEntry[3] = "sw_xue";
					newCard.push(newCardEntry);
				}
			}
			lib.card.list.push(...newCard)
			lib.card.list.push(...lib.card.list.slice())
			lib.card.list.push(...lib.card.list.slice())
		};
		"step 1"
		game.waitForPlayer(function () {
			lib.configOL.number = lib.configOL.player_number;
			/*			lib.configOL.player_number = lib.configOL.hemengaozhan*/
		});
		"step 2"
		if (_status.connectMode) {
			_status.mode = lib.configOL.hemengaozhan_mode;
			if (_status.mode == "normal") {
				//lib.configOL.number = 8;
				//event.replacePile()
			}
			else if (_status.mode == "wuxianhuoli") {
				//lib.configOL.number = 8;
				//event.replacePile()
			}
			else {
				//lib.configOL.number = 8;
				//event.replacePile()
			}
			if (lib.configOL.number < 2) {
				lib.configOL.number = 2;
			}
		} else {
			//TODO:非联机模式逻辑
		}
		event.replacePile()
		"step 3"
		if(typeof _status.extensionMode.oninit === "function") _status.extensionMode.oninit()
		"step 4"
		game.randomMapOL();
		"step 5"
		for (var i = 0; i < game.players.length; i++) {
			game.players[i].ai.shown = 1;//ai暴漏程度
			//不是哥们？你看这么仔细？都看到这里了？
		}
		game.syncState();
		event.trigger("gameStart");
		"step 6"
		var players = get.players(lib.sort.position);
		var info = [];
		for (var i = 0; i < players.length; i++) {
			var ifo = {
				name: players[i].name1,
				name2: players[i].name2,
				identity: players[i].identity,
				nickname: players[i].node.nameol.innerHTML,
			};
			info.push(ifo);
		}
		_status.videoInited = true;
		game.addVideo("init", null, info);
		"step 7"
		event.beginner = _status.firstAct2 || game.zhong || game.zhu || _status.firstAct || game.boss || game.me;
		game.gameDraw(event.beginner, function (player) {
			return 4;
		});
		//TODO: 判断非联机
		//手气卡
		if (_status.connectMode && lib.configOL.change_card) game.replaceHandcards(game.players.slice(0));
		//"step 8"
		//game.broadcastAll((player) => {
		//	player.init("boss_zhugeliang")
		//}, game.me)
		"step 8";
		game.phaseLoop(event.beginner);

		//初始化角色，应该放在init里面
		//var libCharacter = {};
		//var list = [];
		//for (var i = 0; i < lib.configOL.characterPack.length; i++) {
		//	var pack = lib.characterPack[lib.configOL.characterPack[i]];
		//	for (var j in pack) {
		//		if (lib.character[j]) libCharacter[j] = pack[j];
		//	}
		//}
		//for (i in libCharacter) {
		//	if (lib.filter.characterDisabled(i, libCharacter)) continue;
		//	list.push(i);
		//}
		//_status.characterlist = list.slice(0);

		//game.broadcastAll((boss, map) => {
		//	game.boss = [];
		//	for (var i = 0; i < boss.length; i++) {
		//		game.boss.push(game.addPlayer(3 + i, map[i], boss[i]));
		//		lib.playerOL[map[i]] = game.boss[i];
		//		game.boss[i].boss = true;
		//		game.boss[i].node.identity.innerHTML = `<span style='font-family:"xinwei";color:red;font-size:20px;'>敌</span>`;
		//	}
		//}, boss, map);
		//game.players2 = game.players.filter(p => !p.boss);
		window.game = game;
		window.lib = lib;
	},
	chooseMode() {//初始化游戏完成，分配选将逻辑

		const mode = _status.mode.slice(0, 1).toUpperCase() + _status.mode.slice(1);//首字母大写
		if (typeof game['chooseCharacter' + mode + 'OL'] === 'function') {//存在对应的选择角色逻辑就跳转
			game['chooseCharacter' + mode + 'OL']()
			return;
		}
		//反之用默认的
		const next = game.createEvent('chooseCharacter');
		next.set('mode', mode)
		//TODO:添加默认的选择角色逻辑
		next.setContent("Default");
		return next
	},
	modeConfig() {
		game.chooseCharacterNormalOL = function () {
			game.broadcastAll((version) => {
				game.layoutGame();//创建信息栏
				_status.gameInfomation = {};
				_status.gameInfomation.killNum = 0;
				_status.gameInfomation.huanhundan = 1;
				_status.gameInfomation.version = version;
				_status.gameInfomation.newversion = "无法获取";
			}, swTool.extensionVersion);

			try {
				const version = new Promise((resolve, reject) => {
					const timeoutId = setTimeout(() => {
						reject('请求超时');
					}, 2000);
					fetch('http://49.233.171.97:3000/text')
						.then(response => {
							clearTimeout(timeoutId); // 清除超时计时器
							if (!response.ok) {
								reject('无法获取版本信息');
								return "无法获取";
							}

							return response.text();
						})
						.then(version => resolve(version))
						.catch(error => reject(error));
				}).then(result => {
					game.setGameInfo("newversion", result)
				});

			} catch (error) {
				game.setGameInfo("newversion", '无法获取')
				console.error('错误:', error);
			}

			_status.videoInited = true
			lib.playerSkillOL = {}

			game.broadcast((copyCharacter) => {
				if (!window.swTool) {
					window.swTool = { copyCharacter }
				}
				else swTool.copyCharacter = copyCharacter
			}, swTool.copyCharacter)
			_status.playerCharacters = {}
			const initSkillInfo = skills => {
				if (!Array.isArray(skills)) skills = [skills]
				let str = ''
				skills.forEach(s => {
					if (s === 'changeUseSkill') return
					str += get.translation(s) + ' '
				})
				return str
			}
			_status.characterListSelect = Object.keys(swTool.initList(() => { }));
			const characterList = _status.characterListSelect;
			const skillList = game.getSWSkillsList();

			_status.style = {
				innerHTML:/*css*/`
                .player .playerskillList {
                    color: orange;
                    font-weight: 700;
                    text-shadow: 1px 1px black;
                    z-index: 90000000;
                }
                .player:not([data-position="0"]) .playerskillList {
                    width: 70px;
                    height: auto;
                    top: 35%;
                    border-radius: 5px;
                    text-align: center;
                    line-height: 2;
                    left: 20%;
                    padding: 0 10px;
                    font-size: 15px;
                }
                .player[data-position="0"] .playerskillList {
                    top: -30px;
                    left: 15px;
                }
            `
			}

			const [plays, aplays] = swTool.connect_players();
			game.players.forEach(element => element.identity = 'fan');//遍历所有玩家，把他们都设置成反贼
			if (aplays.length > 0) game.zhu = aplays.randomGet()//人机必定是主公
			else game.zhu = plays.randomGet()

			game.broadcastAll((zhu, setSeat) => {

				game.zhu = zhu
				game.zhu.isZhu = true
				game.zhu.identityShown = true
				game.zhu.identity = 'zhu'
				game.zhu.setIdentity('zhu')
				setSeat(game.zhu)
				const players = game.players.filter(p => p !== game.zhu)
				players.forEach((p, i) => {
					p.identity = "fan"
					p.setIdentity("fan")
					p.identityShown = true
				})
				//if (!ui.huanhuazhizhan) {
				//	ui.huanhuazhizhan = ui.create.div(".touchinfo.left", ui.window);
				//}
				//ui.huanhuazhizhan.innerHTML = "无尽模式";

			}, game.zhu, swTool.setPlayersSeat)

			const clp = characterList.randomGets(10);
			game.broadcastAll((list, pls) => {
				pls.forEach((p, i) => {
					if (!p.nickname) {
						lib.character[list[i]][3] = []
						lib.character[list[i]][2] = 4//TODO: 存在疑问？
						p.init(list[i])
						//lib.playerCharacterOL[p.playerid] = list[i];
						//p.addSkill("sw_bossGetSkill");
					}
				})
				game.me.update()
			}, clp, aplays)


			const skillMap = {}
			game.players.forEach(p => {
				skillMap[p.playerid] = skillList.randomGets(parseInt(lib.configOL.hemengaozhan_selects))
				if (p.nickname == "守望" || p.nickname == "神守望") {
					//此处可添加测试性技能

					skillMap[p.playerid].add("sw_test");
					skillMap[p.playerid].add("yimie");
				}
				//skillList.removeArray(skillMap[p.playerid])
				lib.playerSkillOL[p.playerid] = skillMap[p.playerid]
			})
			skillMap[game.zhu.playerid] = [];
			const initPlayers = game.players.map(p => {
				if (p.ws || p === game.me) {
					let avatar
					let nickname
					if (p === game.me) {
						avatar = lib.config.connect_avatar
						nickname = lib.config.connect_nickname
					} else {
						avatar = p.ws.avatar
						nickname = p.nickname
					}
					game.addVideo('initAvatar', null, { avatar, nickname, playerid: p.playerid })
					return [p, avatar, skillMap[p.playerid]]
				}
			}).filter(Boolean)
			game.broadcastAll((players, { me, name, avatar, skill }) => {
				players.forEach(([player, avatar, skill]) => {
					player.nowSkill = skill
					const nickname = player.nickname
					const id = nickname + player.playerid
					swTool.copyCharacter({
						character: avatar,
						hp: 4,
						skills: [],
						name: id,
						translate: nickname
					})
					player.init(id)
				})
				name = name.replace('※', '')
				const id = name + me.playerid
				swTool.copyCharacter({
					character: avatar,
					hp: 4,
					skills: [],
					name: id,
					translate: name
				})
				me.init(id)
				me.update()
				me.nowSkill = skill
			}, initPlayers, { me: game.me, name: lib.config.connect_nickname, avatar: lib.config.connect_avatar, skill: skillMap[game.me.playerid] })

			game.addVideo('init', null, game.players.map(p => {
				return {
					name: p.name1,
					name2: p.name2,
					identity: (p === game.me || p === game.zhu) ? p.identity : 'cai'
				}
			}))


			const next = game.createEvent('chooseCharacter')
			next.setContent(async event => {

				lib.playerCharacterOL = {}
				_status.playerCharacters = {}
				_status.characterlist = characterList.slice()
				_status.skillList = skillList
				_status.skillList2 = skillList.slice()

				game.broadcastAll((time) => {
					ui.arena.classList.add('choose-character');
					event.time = lib.configOL.choose_timeout;
					lib.configOL.choose_timeout = time;//选技能时间调整
				}, lib.configOL.hemengaozhan_more_time);

				const startSkillNum = lib.configOL.hemengaozhan_startNum ? lib.configOL.hemengaozhan_startNum : 3;
				////选技能
				const skList = game.players.map(i => {
					if(i != game.zhu) game.changeState(i, "选初始技能");
					const lt = [];
					for (const skill of skillMap[i.playerid]) lt.push([skill, '<div class="popup text" style="width:calc(100% - 10px);display:inline-block"><div class="skill">【' + get.translation(skill) + "】</div><div>" + lib.translate[skill + "_info"] + "</div></div>"]);
					return [i, ['你可以选择' + get.cnNumber(startSkillNum) + '个初始技能（可以触发“游戏开始时”时机）', [lt, 'textbutton']], parseInt(startSkillNum), true]
				})
				if (game.me != game.zhu) {
					const xuanjineng = await game.me.chooseButtonOL2(skList, function (player, result) {
						if (game.online || player == game.me) game.changeState(player, "选初始技能", true);
					});
					for (const i in xuanjineng.result) {
						const player = lib.playerOL[i]
						const bool = xuanjineng.result[i]
						if (!bool.bool) {
							if (skillMap[player.playerid] && skillMap[player.playerid].length > parseInt(startSkillNum)) skillMap[player.playerid] = skillMap[player.playerid].randomGets(parseInt(startSkillNum));
							continue
						}
						const skills = xuanjineng.result[i].links
						skillMap[player.playerid] = xuanjineng.result[i].links
					}
				}

				//选势力
				const select = lib.group.map(g => ['', '', `group_${g}`])
				const groupList = game.players.map(i => {
					return [i, ['你可以选择一个势力', [select, 'vcard']], 1, false]
				})
				const shili = await game.me.chooseButtonOL(groupList, (player, result) => {
					if (!result) return
					if (player === game.me) {
						player.changeGroup(result.links[0][2].slice(6), false, false);
					}
				}).set('processAI', function () {
					return false
				})
				for (const g in shili.result) {
					if (!shili.result[g].bool) continue
					const player = lib.playerOL[g]
					const group = shili.result[g].links[0][2].slice(6)
					game.broadcastAll((player, group) => {
						lib.character[player.name1][1] = group
						player.changeGroup(group)
						//player.addSkill("xiangxing_baiban");
					}, player, group)
					game.addVideo('flashGroup', player, { group })
				}


				game.broadcastAll((time) => {
					lib.configOL.choose_timeout = time;//选技能完毕时间恢复
				}, event.time);


				game.players.forEach(p => {
					game.broadcastAll((player, name, skill) => {
						//player.addSkill('sw_getSkill')
						player.nowSkill = skill
						player.addSkill(skill)
						lib.character[name][3] = skill
						player.firstCharacter = name
						lib.characterSubstitute[name] = [];
						const skinList = [
							"https://b0.bdstatic.com/ugc/V8res5ZIyEQ1vv7O6Ql19A03d71c8243056672399a4eebd72cf1fa.jpg",
							"https://img0.baidu.com/it/u=2536943837,1492977612&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=616",
							"https://pic.rmb.bdstatic.com/bjh/058dc53124683a55cc1acd72e80a72fc2461.png@h_1280",
							"https://pic.rmb.bdstatic.com/bjh/3560b47e57c89ef4215e02ce2abafe525075.jpeg@h_1280",
							"https://img2.baidu.com/it/u=2136473769,1882314982&fm=253&fmt=auto&app=138&f=JPEG?w=352&h=499",
							"https://img1.baidu.com/it/u=2513486530,1456942170&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=667",
							"https://img2.baidu.com/it/u=1272673039,3136507784&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=750",
							"https://b0.bdstatic.com/ugc/jsiDRNxzSfNyP64A4FO1LA01949e304713fc67579e0dd2df6c77b9.jpg@h_1280",
							"https://img2.baidu.com/it/u=1303694108,1963845908&fm=253&fmt=auto?w=500&h=896",
							"https://pic.rmb.bdstatic.com/bjh/events/6061e59a3b13f5d2fdade78ccf8417c06623.jpeg@h_1280",
							"https://img.picui.cn/free/2025/05/31/683ac4572eab1.jpg",
							"https://img.picui.cn/free/2025/06/01/683c3359707f2.gif",
							"https://img.picui.cn/free/2025/06/02/683d23e530873.gif",
							"https://img.picui.cn/free/2025/06/02/683d23ed7a05a.gif",
						]
						for(let i = 0; i < skinList.length; i++) {
							lib.characterSubstitute[name].push([name + `_shadow${i}`, [`img:${skinList[i]}`]]);
						}

					}, p, p.name1, skillMap[p.playerid])

					_status.playerCharacters[p.playerid] = {
						player: p,
						skills: lib.character[p.name1][3],
						name: (p.nickname && p.nickname.replace('※', '')) || '',
						character: p.name1,
						info: lib.character[p.name1],
						group: p.group,
						sex: p.sex,
					}
					if (game.videoContent.initSkill) {
						game.addVideo('initSkill', p, { skills: skillMap[p.playerid], zhu: p === game.zhu, me: p === game.me })
					}
				})
				_status.playerCharactersSkins = lib.characterSubstitute;

				const aps = game.players.filter(p => p != game.zhu)//非主的所有玩家
				for (var i of aps) {
					i.addSkill("sw_getSkill");
					if(lib.configOL.hemengaozhan_mofaEnhance) i.addSkill("mofaLDW_enhance");
					//i.addSkill("sw_viewTeamHandcard");
					//i.addSkill("sw_getSkillLimit");//限制技能的获取
				}
				game.broadcastAll((map) => {
					game.players.forEach(p => {
						if (!p.storage.sw_getSkillName) p.storage.sw_getSkillName = [];
						for (const abc of map[p.playerid]) {
							p.storage.sw_getSkillName.push(abc);
						}
					})
				}, skillMap);


				var list = ["_sw_viewTeamHand", "_sw_zhuLimit", "_sw_playerLimit"];
				for (var i = 0; i < list.length; i++) {
					game.addGlobalSkill(list[i]);
				}

				//观战和重连同步
				_status.reloadResource = [_status.playerCharacters, _status.gameInfomation, _status.playerCharactersSkins, _status.sw_playersBag, _status.sw_playersInfo]

				game.broadcastAll(() => {
					setTimeout(function () {
						ui.arena.classList.remove('choose-character');
					}, 500);
				})
				_status.videoInited = false

				//game.zhu.die();
			})

		}

	},
	game: {
		updateHTML: function(){
			if(_status.sw_html) return
			_status.sw_html = true
			const style = document.createElement('style')
			style.innerHTML = swTool.backpackHTML
			document.head.appendChild(style)
		},
		clearArena() {
			ui.control.innerHTML = "";
			ui.arenalog.innerHTML = "";
			Array.from(ui.arena.childNodes).forEach(value => {
				if (value == ui.canvas) return;
				if (value == ui.control) return;
				if (value == ui.arenalog) return;
				if (value == ui.roundmenu) return;
				if (value == ui.timer) return;
				if (value == ui.autonode) return;
				if (value == ui.sw_bag) return;
				value.remove();
			});
			ui.sidebar.innerHTML = "";
			ui.cardPile.innerHTML = "";
			ui.discardPile.innerHTML = "";
			ui.special.innerHTML = "";
			ui.ordering.innerHTML = "";
			ui.playerids.remove();
			game.players.length = 0;
			game.dead.length = 0;
			game.me = null;
		},
		createTip: function (text) {
			const clog = ui.create.div('div', '.olskilllog', text, ui.arena)
			clog.css({
				left: "50%",
				transform: "translateX(-50%)",
				zIndex: "100",
				fontSize: "20px",
				backgroundColor: "rgba(0,0,0,.3)",
				padding: "10px",
				top: "25%",
				borderRadius: "5px",
				textShadow: "1px 1px black"
			})
			setTimeout(() => {
				clog.style.opacity = '0'
			}, 4000)
			setTimeout(() => {
				clog.remove()
			}, 6000)
			return clog
		},
		addNewPlayer: async function (name, position = undefined, identity = "zhong", side = null, animation = "zoominanim") {//此处的位置是相对于主公的位置，正数表示右边，负数表示左边,0表示主公左边1个（即在主公的位置，把主公往后推了一个）
			let players = game.players.concat(game.dead);
			let playerCnt = players.length;//总人数

			if(position === undefined) position = Math.floor(Math.random() * playerCnt) + 1

			game.addVideo("addNewPlayer", null, [position, name, animation]);

			game.broadcastAll((id, num, players, character, pos, identity, side) => {
				character = Array.isArray(character) ? character[0] : character;

				ui.arena.setNumber(num + 1);//设置多出一个位置

				if (game.zhu != null) {
					pos = (parseInt(game.zhu.dataset.position) + parseInt(pos) + parseInt(num * num)) % parseInt(num);//计算对于每个人视角下新增随从的相对位置
				}
				if (pos == 0) pos = num;

				players.forEach(value => {
					if (parseInt(value.dataset.position) >= pos) value.dataset.position = parseInt(value.dataset.position) + 1;//将新增随从后面的人位置+1
				});

				let fellow = ui.create.player();
				game.zhuFellow = fellow;
				fellow.playerid = id;
				game.playerMap[fellow.playerid] = fellow;
				lib.playerOL[fellow.playerid] = fellow;
				fellow.dataset.position = pos || playerCnt - 1;

				game.players.push(fellow);
				ui.arena.appendChild(fellow);
				game.arrangePlayers();
				if (character) fellow.init(character);

				fellow.side = side;
				fellow.identity = identity;
				fellow.setIdentity(identity);
				fellow.identityShown = true;
			}, get.id(), playerCnt, players, name, position, identity, side);

			await game.zhuFellow.directgain(get.cards(4));
			await game.delayx()
			return game.zhuFellow
		},
		removePlayer: async function (player) {
			let players = game.players.concat(game.dead);
			let playerCnt = players.length - 1;//随从后的总人数

			game.broadcastAll((num, players, diePlayer) => {
				ui.arena.setNumber(num);//设置多出一个位置

				players.forEach(value => {
					if (parseInt(value.dataset.position) > diePlayer.dataset.position) value.dataset.position = parseInt(value.dataset.position) - 1;//将新增随从后面的人位置+1
				});

				game.players.remove(diePlayer);
				game.dead.remove(diePlayer);
				game.arrangePlayers();
				delete game.playerMap[diePlayer.playerid];
				delete lib.playerOL[diePlayer.playerid];
				diePlayer.delete();

			}, playerCnt, players, player);
			await game.delayx()
		},
		refreshInfo: function () {
			game.broadcast((info) => {
				_status.gameInfomation = info;
			}, _status.gameInfomation)
		},
		setGameInfo: function(name, content){
			_status.gameInfomation[name] = content
			game.refreshInfo()
		},
		getRoomInfo: function (uiintro) {
				uiintro.add('<div class="text chat">游戏模式：' + (lib.configOL.hemengaozhan_mode == "normal" ? "标准模式" : "无限火力"));
				uiintro.add('<div class="text chat">初始技能池数：' + lib.configOL.hemengaozhan_selects);
				uiintro.add('<div class="text chat">初始技能上限：' + lib.configOL.hemengaozhan_startNum);
				uiintro.add('<div class="text chat">还魂丹立即复活：' + (lib.configOL.hemengaozhan_reviveMode == true ? "是" : "否"));
				uiintro.add('<div class="text chat">全扩获取技能：' + (lib.configOL.hemengaozhan_allSkills == true ? "是" : "否"));
				uiintro.add('<div class="text chat">火速加群体验最新扩展！');
				/*
				uiintro.add('<div class="text chat">双将模式：' + (lib.configOL.double_character ? "开启" : "关闭"));
				if (lib.configOL.identity_mode != "zhong") {
					if (lib.configOL.identity_mode == "stratagem") {
						uiintro.add('<div class="text chat">首轮强化：' + (lib.configOL.round_one_use_fury ? "开启" : "关闭"));
					} else if (lib.configOL.identity_mode != "purple") {
						uiintro.add('<div class="text chat">双内奸：' + (lib.configOL.double_nei ? "开启" : "关闭"));
						if (lib.configOL.identity_mode != "stratagem") {
							uiintro.add(
								`<div class="text chat">加强主公：${(() => {
									switch (lib.configOL.enhance_zhu) {
										case "sixiang":
											return "四象标记";
										case "specific":
											return "专属技能";
										default:
											return "关闭";
									}
								})()}`
							);
							uiintro.add('<div class="text chat">平民身份：' + (lib.configOL.enable_commoner ? "开启" : "关闭"));
						}
						uiintro.add('<div class="text chat">年机制：' + (lib.configOL.enable_year_limit ? "开启" : "关闭"));
					}
				} else {
					uiintro.add('<div class="text chat">卡牌替换：' + (lib.configOL.zhong_card ? "开启" : "关闭"));
				}
				var last = uiintro.add('<div class="text chat">出牌时限：' + lib.configOL.choose_timeout + "秒");
				if (lib.configOL.banned.length) {
					last = uiintro.add('<div class="text chat">禁用武将：' + get.translation(lib.configOL.banned));
				}
				if (lib.configOL.bannedcards.length) {
					last = uiintro.add('<div class="text chat">禁用卡牌：' + get.translation(lib.configOL.bannedcards));
				}
				*/
				//last.style.paddingBottom = "8px";
			},
		getSWSkillsList: function (player = undefined, isAll = false) {//全扩获取技能，只会找在武将牌上存在的技能
			const banSkill = ["kunyu", "twfuxi", "dclieqiong", "new_dclieqiong",
				"iwasawa_mysong", "twfengpo", "twgongge", "fenxin_old",
				"shizuru_nianli", "vtbleyu", "chuanxin", "olddanshou",
				"dcgeyuan", "pszhonghu", "kotarou_aurora", "pszizhong",
				"yimie", "jxzhaoluan", "jsrgshenchong", "boss_juejing",
				"duanchang", "yjyibing", "noname_duocai", "nshuanhuo",
				"yuu_lveduo", "jsrgtuigu", "dcsbpingliao", "dcliuzhuan",
				"dcyouzhan", "shencai", "tyshencai", "spfengyin",
				"dcwumei", "zombielongmu", "cazhaoshao", "nsjihui", "olshenchong",

			];
			var skills = [];
			var list = {};
			list = _status.characterListSelect
			if (!isAll) list = _status.characterListSelect || Object.keys(swTool.initList()) || get.charactersOL();
			else {
				const libCharacter = {}
				lib.connectCharacterPack.forEach(p => {
					const pack = lib.characterPack[p]
					for (const c in pack) {
						if (lib.character[c]) libCharacter[c] = pack[c];
					}
				})
				list = Object.keys(libCharacter)
			}
			for (var i of list) {
				if (i.indexOf("gz_jun") == 0) continue;
				for (var j of lib.character[i][3]) {//j为技能名
					if (!lib.translate[j] || !lib.translate[j + "_info"]) continue;
					//if (j.indexOf("sw_") == 0 || j.indexOf("_sw_") == 0 || j.indexOf("qd_") == 0) continue;
					var skill = lib.skill[j];
					if (!skill || skill.zhuSkill) continue;
					//if (skill.ai && (skill.ai.combo || skill.ai.notemp || skill.ai.neg)) continue;

					if (player != undefined && player.getSkills(true, false, false).includes(j)) continue;
					if (banSkill.includes(j)) continue;
					//var info = get.translation(j + "_info");
					skills.add(j);
				}
			}
			//console.log(skills.includes("mofaLDW"));
			return skills;
		},
		layoutGame: function () {
			game.updateHTML()

			if (!ui.count_dan) {
				ui.count_dan = ui.create.system("信息", null, true, true);
			}
			lib.setPopped(
				ui.count_dan,
				function () {
					var uiintro = ui.create.dialog("hidden");
					uiintro.add("游戏信息");
					//var table = ui.create.div(".bosschongzheng");
					let info = `<div class="text center" style="color: gray;">貌似无法获取最新版本号哦...</div>`;

					if (get.gameInfo(3) && get.gameInfo(3) != "无法获取") {
						if (get.gameInfo(3) == get.gameInfo(2)) {
							info = `<div class="text center" style="color: #FFD700;">已是最新的游戏版本！</div>`;
						}
						else {
							info = `<div class="text center" style="color: #FF6666;">该版本已过时，最新版本: v${get.gameInfo(3)}</div>`;
						}
					}

					uiintro.add(`<div class="text center">还魂丹剩余数量：${get.gameInfo(1)}</div>`);
					uiintro.add(`<div class="text center">BOSS击杀次数：${get.gameInfo(0)}</div>`);
					uiintro.add(`<div class="text center">游戏版本：${get.gameInfo(2)}</div>`);
					uiintro.add(`<div class="text center">${info}</div>`);

					uiintro.add(ui.create.div(".placeholder.slim"));


					return uiintro;
				},
				180
			);
			if (!ui.changeSkin) {
				ui.changeSkin = ui.create.system(
					"换肤",
					function () {
						if (game.online) {
							game.send("changeSkinFun", game.me);
						}
						else {
							var playerr = game.me;
							game.broadcastAll((player) => {
								if (lib.characterSubstitute[player.firstCharacter]) {
									var num = Math.floor(Math.random() * lib.characterSubstitute[player.firstCharacter].length);
									player.changeSkin({ characterName: player.firstCharacter }, player.firstCharacter + "_shadow" + num);
								}
							}, playerr);
							game.log(playerr.nickname, "换肤成功！");
						}
					},
					true,
					true
				);
			}
			lib.setPopped(
				ui.changeSkin,
				null,
				120
			);
			if(!ui.sw_bag) ui.sw_bag = ui.create.bagButton()
		},
		newBossList: async function (bossList, zhuMoreHp = 0) {
			if(!bossList || bossList.length == 0) return
			var boss = bossList.find(item => item.identity === 'zhu');
			if (!boss) boss = bossList.shift()

			game.broadcastAll((boss, p, zhuMoreHp) => {
				p.revive(null, false);
				p.uninit();
				p.init(boss);
				if (zhuMoreHp != 0 && boss != "boss_sunce") {
					p.maxHp = p.maxHp + zhuMoreHp;
					p.hp = p.hp + zhuMoreHp;
				}
				p.update();
			}, boss.name, game.zhu, zhuMoreHp)

			await game.delayx()

			const bossFellows = bossList.filter(item => item.identity !== 'zhu');
			for (let item of bossFellows) {
				if(!item.name) continue
				if(!item.identity) item.identity = 'zhong'
				if (item.location === undefined) item.location = 1
				const fellow = await game.addNewPlayer(item.name, item.location, item.identity)
				await fellow.addSkill("sw_xionge")//随从加强
				game.triggerEnter(fellow);
			}
		},
		debug: function(){
			game.setGameInfo("killNum", 3)
			game.setGameInfo("huanhundan", 100)
			game.zhu.die()
		},
		openBag: function(player = game.me) {
			if(player === game.me) {
				game.changeState(player, "扒拉背包")
			}
			const talents = player.getSkills(null, false, false).filter(skill => {
				const info = get.info(skill);
				if (!info || info.charlotte || !get.skillInfoTranslation(skill, player).length) return false;
				return true;
			});
			const bag = player.getBagItemList()
			game.pause2();
			//tip窗口
			let tip = document.querySelector('.sw_skillInfoDesc');
			if (!tip) {
				tip = ui.create.div('.sw_skillInfoDesc');
				document.body.appendChild(tip);
			}
			tip.innerHTML = `<p style='color: gold;margin: 2%;'> </p><p style='margin: 2%;'> </p>`;
			tip.style.display = "none";
			tip.classList.remove("fade-out");
			//背景
			let bg = ui.create.div(".swContainer.backpack", ui.window, function (e) {
				e.stopPropagation();
				e.preventDefault();
				tip.style.display = "none";
				tip.classList.remove("fade-out");
				this.delete(400);
				if(player === game.me) {
					game.changeState(player, "扒拉背包", true)
				}
				game.resume2();
			});
			//主界面
			let backpack = ui.create.div(".mainBackpack", bg, function (e) {
				e.stopPropagation();
			});
			//内容面板
			let bagContent = ui.create.div(".bagContent", backpack);
			//内容面板分两栏，左右，横向排列元素
			let leftPanel = ui.create.div(".bagPanel", bagContent);
			let rightPanel = ui.create.div(".bagPanel", bagContent);

			let subtitle = ui.create.div(".subtitle", leftPanel);
			subtitle.textContent = `个人信息`;
			let selfContainer = ui.create.div(".sw_Container", leftPanel);
			// Object.assign(selfContainer.style, {
			// 	"align-items": "center",
			// });

			// 创建头像区域
			let avatar = ui.create.div(".avatar", selfContainer);
			let avatarImg = ui.create.div(".avatarImg", avatar);
			let avatarName = ui.create.div(".avatarName", avatar);
			avatarImg.style.backgroundImage = player.node.avatar.style.backgroundImage;
			avatarName.textContent = player.nickname

			let sw_info = ui.create.div(".sw_info", selfContainer);
			ui.create.div(".level", "等级：1", sw_info);
			ui.create.div(".money", `金币：${player.getMoney()}`, sw_info);
			ui.create.div(".title", "称号：暂无", sw_info);


			//右侧面板
			let subtitleRight = ui.create.div(".subtitle", rightPanel);
			subtitleRight.textContent = `背包`;
			let bagContainer = ui.create.div(".sw_Container", rightPanel);
			Object.assign(bagContainer.style, {
				height: "44%",
			});
			let bagList = ui.create.div(".backpackContainer", bagContainer);

			for(let key in bag) {
				const name = get.translation(key) || key || "undefined"
				const count = bag[key] || 1
				let item = ui.create.div(".backpackItem", bagList);
				let itemName = ui.create.div(".itemName", item);
				let itemCount = ui.create.div(".itemCount", item);
				itemName.innerHTML = name
				itemCount.innerHTML = `×${count}`
			}

			let subtitleRight2 = ui.create.div(".subtitle", rightPanel);
			subtitleRight2.textContent = `技能`;
			let talentContainer = ui.create.div(".sw_Container", rightPanel);
			Object.assign(talentContainer.style, {
				height: "40%",
			});
			let talentList = ui.create.div(".skillContainer", talentContainer);

			for(let key in talents) {
				let skill = talents[key]
				if(!lib.skill[skill]) continue;
				let item = ui.create.div(".skillItem", talentList);
				item.textContent = get.translation(skill)

				// let tip = ui.create.div(".skillTip", item);
				// tip.innerHTML = get.skillInfoTranslation(skill, player);
				var fadeTimer = null;
				var fadeDelayTimer = null;
				item.addEventListener("mouseenter", function (e) {
					//if (tip.innerHTML == "") return;
					tip.innerHTML = `<p style='color: gold;margin: 2%;'>${get.translation(skill)}</p><p style='margin: 2%;'>${get.skillInfoTranslation(skill, player)}</p>`;
					tip.style.display = "block";
					clearTimeout(fadeDelayTimer);
					clearTimeout(fadeTimer);
					tip.classList.remove("fade-out");
					// let rect = talentList.getBoundingClientRect();
					// if (e.clientY < rect.top + rect.height / 2) {
					// 	tip.style.top = "110%";
					// } else {
					// 	tip.style.bottom = "110%";
					// }
				});
				item.addEventListener("mouseleave", function (e) {
					//tip.style.display = "none";
					clearTimeout(fadeDelayTimer);
					clearTimeout(fadeTimer);
					fadeDelayTimer = setTimeout(() => {
						tip.classList.add("fade-out");
						fadeTimer = setTimeout(() => {
							tip.style.display = "none";
							tip.classList.remove("fade-out");
						}, 300);
					}, 300);
				});
			}

		},
		changeState: function(player, stateName = undefined, clear = false) {
			if(game.online) {
				game.send("changeState", player, stateName, clear);
			}
			else {
				if(!player.isOnline() && player !== game.me) return
				game.broadcastAll((player, stateName, clear) => {
					function formatText(strList) {
						var str = "";
						for(let i in strList) {
							if(typeof strList[i] != "String") strList[i] = strList[i].toString();
							if(str == "") str += strList[i];
							else str += "、" + strList[i];
						}
						return "正" + str + "中";
					}
					function change(item) {
						if(item.textContentTemp && item.textContentNum) {
							item.textContent = formatText(item.textContentTemp) + [".", "..", "..."][item.textContentNum - 1]
							item.textContentNum = item.textContentNum % 3 + 1
						}
					}
					function clearTimer() {
						if(_status.sw_playerStateInterval[player.playerid]) {
							clearInterval(_status.sw_playerStateInterval[player.playerid])
							_status.sw_playerStateInterval[player.playerid] = null
						}
					}
					let item = player?.node?.sw_playerState;
					if(document.body.classList.contains('layout-false') && (game.layout == "mobile" || game.layout == "long")) {
						document.body.classList.remove('layout-false'); //清除之前的
						document.body.classList.add('layout-true');
					}
					else if(document.body.classList.contains('layout-true') && game.layout != "mobile" && game.layout != "long"){
						document.body.classList.remove('layout-true'); //清除之前的
						document.body.classList.add('layout-false');
					}
					else if(!document.body.classList.contains('layout-true') && !document.body.classList.contains('layout-false')) {
						document.body.classList.add('layout-' + (game.layout == "mobile" || game.layout == "long"));
					}
					if(!item) {
						// item = ui.create.div('.sw_playerState', player === game.me ? player.node.avatar : player)
						// if(player === game.me) item.style.top = "24px"
						item = ui.create.div('.sw_playerState', player)
						player.node.sw_playerState = item
					}
					if(!_status.sw_playerStateInterval) _status.sw_playerStateInterval = {}
					item.textContentNum = 1
					if(!item.textContentTemp) item.textContentTemp = []
					if(stateName === undefined) {
						item.textContentTemp = []
						item.textContent = ""
						clearTimer()
					}
					else if(clear) {
						item.textContentTemp = item.textContentTemp.filter(item => item !== stateName);
						if(item.textContentTemp.length == 0) {
							item.textContent = ""
							clearTimer()
						}
						else change(item)
					}
					else {
						if(!item.textContentTemp.includes(stateName)) item.textContentTemp.push(stateName)
						clearTimer()
						change(item)
						_status.sw_playerStateInterval[player.playerid] = setInterval(change,1000, item);
					}
				}, player, stateName, clear)
			}
		},
		refreshAllPlayersBag: function() {
			game.broadcastAll((bag) => {
				_status.sw_playersBag = bag
			}, _status.sw_playersBag)
		},
		refreshAllPlayersInfo: function() {
			game.broadcastAll((info) => {
				_status.sw_playersInfo = info
			}, _status.sw_playersInfo)
		},
	},
	element: {
		player: {
			setNickname(str) {
				this.node.nameol.innerHTML = (str || this.nickname || "").slice(0, 12);
				if((this.node.nameol.innerHTML.includes(" - 托管") || this.node.nameol.innerHTML.includes(" - 离线")) && !game.online) game.changeState(this, undefined, true)
				return this;
			},
			changeCharacter(newPairs, log = true) {
				if (!Array.isArray(newPairs)) {
					console.warn(`警告：Player[${this.name}].changeCharacter填写了一个错误的参数:`, newPairs);
					return;
				}
				for (let name of newPairs) {
					if (!lib.character[name]) {
						console.warn(`警告：Player[${this.name}]试图将武将牌变更为不存在的武将:`, name);
						return;
					}
				}
				if(this == game.zhu) {
					this.chat("孩子们，我是不会换的")
					return
				}
				const next = game.createEvent("changeCharacter");
				next.player = this;
				next.newPairs = newPairs;
				next.log = log;
				next.setContent("changeCharacter");
				return next;
			},
			$dieAfter: function () {
				if (_status.video) return;
				if (!this.node.dieidentity) {
					var str;
					if (this.special_identity) {
						str = get.translation(this.special_identity);
					} else {
						//str = get.translation(this.identity + "2");
						str = "";
					}
					var node = ui.create.div(".damage.dieidentity", str, this);
					if (str == "野心家") {
						node.style.fontSize = "40px";
					}
					ui.refresh(node);
					node.style.opacity = 1;
					this.node.dieidentity = node;
				}
				var trans = this.style.transform;
				if (trans) {
					if (trans.indexOf("rotateY") != -1) {
						this.node.dieidentity.style.transform = "rotateY(180deg)";
					} else if (trans.indexOf("rotateX") != -1) {
						this.node.dieidentity.style.transform = "rotateX(180deg)";
					} else {
						this.node.dieidentity.style.transform = "";
					}
				} else {
					this.node.dieidentity.style.transform = "";
				}
			},
			dieAfter: function (source) {
				if (get.population("fan") == 0) {
					if (lib.configOL.hemengaozhan_reviveMode && lib.configOL.hemengaozhan_reviveMode == true && get.gameInfo(1) > 0) {
						// var next = game.createEvent("hmaz_revivePlayer", false);
						// next.setContent("revivePlayer");
					}
					else game.over(false)
				}
				return
			},
			dieAfter2: function (source) {
				game.broadcastAll(() => {
					lib.mode[lib.configOL.mode] ??= {}
					lib.mode[lib.configOL.mode].config ??= {}
					lib.mode[lib.configOL.mode].config.dierestart = false//死亡后不显示退出房间，临时解决方案
				})
				if (this === game.zhu) {
					var next = game.createEvent("hmaz_nextLevel", false);
					next.setContent(async function(event) {
						var next = game.createEvent("hmaz_clearStates", false);
						next.setContent("clearStates");
						await next;

						var next = game.createEvent("hmaz_revivePlayer", false);
						next.setContent("revivePlayer");
						await next;

						var next = game.createEvent("hmaz_gainPassReward", false);
						next.setContent("gainPassReward");
						await next;

						var next = game.createEvent('hmaz_spawnChest');
						next.setContent("spawnChest");
						await next;

						var next = game.createEvent("hmaz_nextBoss", false);
						next.setContent("nextBoss");
						await next;
					});
				}
				else if(lib.character && ((this.name1 && lib.character[this.name1].dieClear) || (this.name2 && lib.character[this.name2].dieClear))) {
					var next = game.createEvent("hmaz_removePlayer", false);
					//next.set("playerr", this)
					next.setContent(async function(event) {
						const tar = event.getParent().player
						if(tar) await game.removePlayer(tar)
					});
					//event.getParent().player
				}
				else if(this.identity == "fan"){
					if (lib.configOL.hemengaozhan_reviveMode && lib.configOL.hemengaozhan_reviveMode == true && get.gameInfo(1) > 0) {
						var next = game.createEvent("hmaz_revivePlayer", false);
						next.setContent("revivePlayer");
					}
				}
			},
			addItem: function(itemName, count = 1, log = true) {
				if(itemName === undefined) return
				const id = this.playerid;
				_status.sw_playersBag ??= {};
				const bag = _status.sw_playersBag[id] ??= {};
				bag[itemName] = (bag[itemName] ?? 0) + count;
				if(log) game.log(this, "获得了", "#y" + `${get.translation(itemName)}×${count}`)
				game.refreshAllPlayersBag()
			},
			removeItem: function(itemName, count = 1, log = true) {
				if(itemName === undefined) return
				const id = this.playerid
				const bag = _status.sw_playersBag?.[id];
				if (!bag || !bag[itemName]) return;
				bag[itemName] -= count;
				if (bag[itemName] <= 0) delete bag[itemName];
				if(log) game.log(this, "失去了", "#y" + `${get.translation(itemName)}×${count}`)
				game.refreshAllPlayersBag()
			},
			hasItem: function(itemName) {
				if(itemName === undefined) return false
				const id = this.playerid
				if(!_status.sw_playersBag) _status.sw_playersBag = {}
				if(!_status.sw_playersBag[id]) _status.sw_playersBag[id] = {}
				return _status.sw_playersBag[id][itemName] ? true : false
			},
			getBagItemList: function() {
				const id = this.playerid
				if(!_status.sw_playersBag) _status.sw_playersBag = {}
				if(!_status.sw_playersBag[id]) _status.sw_playersBag[id] = {}
				const bag = _status.sw_playersBag[id]
				return bag
			},
			addInfo: function(key, value) {
				if(key === undefined) return
				const id = this.playerid
				_status.sw_playersInfo = _status.sw_playersInfo || {};
				const info = _status.sw_playersInfo[id] = _status.sw_playersInfo[id] || {};
				const oldVal = info[key];
				if (typeof value === 'number') {
					info[key] = (typeof oldVal === 'number' ? oldVal : 0) + value;
				}
				else if (Array.isArray(value)) {
					info[key] = Array.isArray(oldVal) ? oldVal.concat(value) : [...value];
				}
				else if (typeof value === 'object' && value !== null) {
					info[key] = { ...(typeof oldVal === 'object' && oldVal !== null ? oldVal : {}), ...value };
				}
				else {
					info[key] = value;
				}
				game.refreshAllPlayersInfo()
			},
			removeInfo: function(key, value) {
				if(key === undefined) return
				const id = this.playerid
				if (!_status.sw_playersInfo || !_status.sw_playersInfo[id]) return;
				const info = _status.sw_playersInfo[id];
				const oldVal = info[key];
				if (typeof value === 'number') {
					if (typeof oldVal === 'number') {
						info[key] = oldVal - value;
					}
				}
				else if (Array.isArray(value)) {
					if (Array.isArray(oldVal)) {
						info[key] = oldVal.filter(item => !value.includes(item));
					}
				}
				else if (typeof value === 'object' && value !== null) {
					if (typeof oldVal === 'object' && oldVal !== null) {
						for (let prop in value) {
							delete oldVal[prop];
						}
						info[key] = oldVal;
					}
				}
				else {
					delete info[key];
				}
				game.refreshAllPlayersInfo()
			},
			getMoney: function() {
				const id = this.playerid
				if (!_status.sw_playersInfo || !_status.sw_playersInfo[id] || !_status.sw_playersInfo[id]["money"]) return 0
				return _status.sw_playersInfo[id]["money"]
			},
		},
		content: {
			revivePlayer: async function (event) {
				var targets = [];
				var dead = game.dead.filter(target => target.identity == "fan").slice(0);
				if (get.gameInfo(1) > 0) {
					for (var i = 0; i < dead.length && get.gameInfo(1) > 0; i++) {
						if (dead[i] != game.zhu && !dead[i].side) {
							if (dead[i].maxHp <= 0) {
								game.broadcastAll((player) => {
									player.maxHp = 1;
									player.update();
								}, dead[i]);
							}
							targets.push(dead[i]);
							game.setGameInfo("huanhundan", get.gameInfo(1) - 1)
						}
					}
				}
				//game.zhu.lose(game.zhu.getCards("hej"))._triggered = null;
				while (targets.length) {
					var target = targets.shift();
					game.createTip(`【${target.nickname || "电脑玩家"}】已被还魂丹复活！`);

					game.broadcastAll((p) => {
						p.revive(Math.min(4, p.maxHp));
						p.update();
					}, target)

					target.draw(4, false);
					target.$draw(4);
					await game.delay(2)
				}
			},
			spawnChest: async function (event) {
				const select = [
					{ name: "null", weight: 10 },
					{ name: "sw_silverchest", weight: 50 },
					{ name: "sw_goldchest", weight: 30 },
					{ name: "sw_diamondchest", weight: 10 },
					{ name: "sw_legendchest", weight: 1 },
					{ name: "sw_ironchest", weight: 1 },
				];
				var ll = "null";
				const totalWeight = select.reduce((sum, item) => sum + item.weight, 0);
				let random = Math.random() * totalWeight;
				for (let i = 0; i < select.length; i++) {
					random -= select[i].weight;
					if (random < 0) {
						ll = select[i].name;
						break;
					}
				}
				if (ll != "null") await game.addNewPlayer(ll, undefined, "nei");
			},
			clearStates: async function(event){
				const playersCopy = game.players.slice();
				for(let ply of playersCopy) {
					if(ply.identity == "zhong") {
						await ply.die()
						await game.delay(1)
					}
				}

				const allPlayers = game.players.concat(game.dead).sortBySeat();
				for (const current of allPlayers) {
					if (current && current.identity == "zhong" || (current.identity == "nei" && current.isDead())) {
						await game.removePlayer(current);
					}
					else if(current){
						current.removeSkill("sw_huisheng");
						current.removeSkill("mofaLDW");
						current.removeSkill("boss_hujia_baiban");
						if (game.zhu.name1 == "sw_xingshen_jinniu" || game.zhu.name2 == "sw_xingshen_jinniu") {
							current.removeSkill("sw_biyi_yuan_ban");
							current.removeSkill("sw_biyi_yang_ban");
						}
					}
				}

			},
			nextBoss: async function(event) {
				var evt = _status.event.getParent("phaseUse");
				if (evt && evt.name == "phaseUse") {
					evt.skipped = true;
				}
				var evt = _status.event.getParent("phase");
				if (evt && evt.name == "phase") {
					evt.finish();
				}

				//定义下一关的BOSS
				const select = [
					{ list: [{ name: "boss_zhenji" }], weight: 2 },
					{ list: [{ name: "boss_zhugeliang" }], weight: 2 },
					{ list: [{ name: "boss_caiwenji" }], weight: 2 },
					{ list: [{ name: "boss_zuoci" }], weight: 1 },
					{ list: [{ name: "boss_caocao" }], weight: 1 },
					{ list: [{ name: "boss_liubei" }], weight: 1 },
					{ list: [{ name: "boss_sunce" }], weight: 1 },
					{
						list: [
							{ name: "boss_jiaxu" },
							{ name: "sw_sangshi"},
							{ name: "sw_pingmin" },
							{ name: "sw_pingmin", location: 0 },
						],
						weight: 4
					},
				];
				//   || _status.selectTwelveStar.length == 0
				if(!_status.selectTwelveStar) {
					_status.selectTwelveStar = [
						{
							list: [
								{ name: "sw_xingshen_baiyang" },
								{ name: "boss_taotie" },
							],
							weight: 1
						},
						{
							list: [
								{ name: "sw_xingshen_jinniu" },
								{ name: "sw_yuan" },
								{ name: "sw_yang", location: 0 },
							],
							weight: 1
						},
						{
							list: [
								{ name: "sw_xingshen_shuangzi" },
								{ name: "sw_castor" },
								{ name: "sw_pollux", location: 0 },
							],
							weight: 1
						},
						{
							list: [
								{ name: "sw_xingshen_sheshou" },
								{ name: "sw_kuoleita" },
							],
							weight: 13
						},
						{
							list: [
								{ name: "sw_xingshen_jvxie" },
								{ name: "sw_qilin" },
							],
							weight: 9
						},
						{
							list: [
								{ name: "sw_xingshen_shizi" },
							],
							weight: 6
						},
						{
							list: [
								{ name: "sw_xingshen_chunv" },
							],
							weight: 400
						},
						{
							list: [
								{ name: "sw_xingshen_tianxie" },
								{ name: "sw_xueyi" },
							],
							weight: 400
						},
						{
							list: [
								{ name: "sw_xingshen_shuangyu" },
							],
							weight: 400
						},
					];
				}

				var selectTwelveStar = _status.selectTwelveStar
				let killNum = get.gameInfo(0);
				var nextBossList = [{ name: _status.characterListSelect.randomGets(1)[0] }]
				if (killNum % 5 == 0) {//大BOSS关=============
					const totalWeight = select.reduce((sum, item) => sum + item.weight, 0);
					let random = Math.random() * totalWeight;
					for (let i = 0; i < select.length; i++) {
						random -= select[i].weight;
						if (random < 0) {
							nextBossList = select[i].list;
							break;
						}
					}
				}
				else if (killNum % 5 == 4) {//十二星神BOSS关=============
					if(_status.selectTwelveStar.length != 0){
						const totalWeight = selectTwelveStar.reduce((sum, item) => sum + item.weight, 0);
						let random = Math.random() * totalWeight;
						for (let i = 0; i < selectTwelveStar.length; i++) {
							random -= selectTwelveStar[i].weight;
							if (random < 0) {
								nextBossList = selectTwelveStar[i].list;
								selectTwelveStar.splice(i, 1);
								break;
							}
						}
						_status.selectTwelveStar = selectTwelveStar
					}

				}

				await game.newBossList(nextBossList, (Math.min(Math.floor(killNum / 2), 8)))

				let listt = game.getSWSkillsList(game.zhu, lib.configOL.hemengaozhan_allSkills)
					.filter(function (i) {
						return !game.zhu.hasSkill(i, null, null, false);
					})
					.randomGets(killNum);
				listt = listt.concat(["sw_getHuihe", "sw_xionge"])
				if (killNum > 5) listt.push("sw_bossGetSkill2");//狂暴技能
				await game.zhu.addSkills(listt);

				game.zhu.lose(game.zhu.getCards("hej"))._triggered = null;
				game.zhu.gain(get.cards(4 + Math.min(killNum, 8)))._triggered = null;
				game.triggerEnter(game.zhu);
				game.zhu.checkMarks();
				game.zhu.insertPhase();

				game.players.filter(p => p.identity == "fan").forEach(i => {
					i.addMark("sw_getSkill", 3);
				})
			},
			gainPassReward: async function(event) {
				//game.broadcastAll(() => {
				//	ui.arena.setNumber(parseInt(ui.arena.dataset.number) + 1);
				//	var fellow = game.addFellow(1, "zhaoyun", "zoominanim");
				//	fellow.directgain(get.cards(4));
				//	fellow.side = true;
				//	fellow.identity = "zhong";
				//	fellow.setIdentity("zhong");
				//	fellow.identityShown = true;
				//	fellow.node.identity.classList.remove("guessing");
				//	game.addVideo("setIdentity", fellow, "zhong");
				//})
				//var evt = trigger.getParent("phaseUse");
				//if (evt && evt.name == "phaseUse") {
				//	evt.skipped = true;
				//}
				//var evt = trigger.getParent("phase");
				//if (evt && evt.name == "phase") {
				//	game.log(evt.player, "结束了回合");
				//	evt.finish();
				//	evt.untrigger(true);
				//}
				game.setGameInfo("killNum", get.gameInfo(0) + 1)
				game.broadcastAll((mm) => {
					var str = "BOSS 已被击杀！击杀次数：" + mm
					if ((mm + 1) % 3 == 0) str += "，所有玩家技能上限+1";
					game.createTip(str);
				}, get.gameInfo(0))
				var targets = game.filterPlayer(function (current) {
					return current.isIn() && current.identity == "fan";
				}).sortBySeat(game.zhu || player);

				for(var p of targets) {
					p.addInfo("money", 50)
				}

				if ((get.gameInfo(0) + 1) % 3 == 0) {
					for (var p of targets) {
						p.storage.sw_getSkillMaxcnt++
						p.addInfo("money", 50)
					}
				}
				var rewards = [
					{
						text: "回复1点体力并摸一张牌",
						weight: 3,
						action(target) {
							target.recover();
							target.draw();
						}
					},
					{
						text: "摸三张牌",
						weight: 3,
						action(target) {
							target.draw(3);
						}
					},
					{
						text: "将一张防具牌置入装备区并摸一张牌",
						weight: 3,
						action(target) {
							let card = get.cardPile(card => get.subtype(card) == "equip2" && !get.cardtag(card, "gifts"));
							if (card) target.equip(card);
							target.draw();
						}
					},
					{
						text: "将一张武器牌置入装备区并摸一张牌",
						weight: 3,
						action(target) {
							let card = get.cardPile(card => get.subtype(card) == "equip1" && !get.cardtag(card, "gifts"));
							if (card) target.equip(card);
							target.draw();
						}
					},
					{
						text: "回复2点体力并弃置一张牌",
						weight: 4,
						action(target) {
							target.recover(2);
							target.chooseToDiscard("he", true);
						}
					},
					{
						text: "摸五张牌，然后弃置三张牌",
						weight: 3,
						action(target) {
							target.draw(5);
							target.chooseToDiscard(3, "he", true);
						}
					},
					{
						text: "获得两张锦囊牌",
						weight: 3,
						action(target) {
							let list = [];
							while (list.length < 2) {
								let card = get.cardPile(c => !list.includes(c) && get.type(c) == "trick");
								if (!card) break;
								list.push(card);
							}
							if (list.length) target.gain(list, "gain2", "log");
						}
					},
					{
						text: "获得五张基本牌",
						weight: 3,
						action(target) {
							let list = [];
							while (list.length < 5) {
								let card = get.cardPile(c => !list.includes(c) && get.type(c) == "basic");
								if (!card) break;
								list.push(card);
							}
							if (list.length) target.gain(list, "gain2", "log");
						}
					},
					{
						text: "失去1点体力，然后摸五张牌",
						weight: 4,
						action(target) {
							target.loseHp();
							target.draw(5);
						}
					},
					{
						text: "失去体力至1点，然后摸七张牌",
						weight: 4,
						gain: 30,
						action(target) {
							let damage = target.hp - 1;
							if (damage > 0) target.loseHp(damage);
							target.draw(7);
						}
					},
					{
						text: "从游戏外获得两张【桃园结义】",
						weight: 3,
						action(target) {
							let cards = [];
							while (cards.length < 2) {
								const card = game.createCard2("taoyuan", "heart", 1);
								cards.push(card);
							}
							if (cards.length) target.gain(cards, "gain2");
						}
					},
					{
						text: "获得五点“灵气”",
						weight: 3,
						action(target) {
							target.addMark("sw_getSkill", 5);
						}
					},
					{
						text: "获得两点护甲",
						weight: 4,
						action(target) {
							target.changeHujia(2);
						}
					},
					{
						text: "获得一个不计上限的随机技能",
						weight: 2,
						cost: 50,
						action(target) {
							let skills = game.getSWSkillsList(target).randomGets(1);
							if (skills.length == 0) game.log(target, "没有技能可得");
							else {
								event.videoId = lib.status.videoId++;
								target.addSkills(skills[0]);
							}
						}
					},
					{
						text: "获得还魂丹一个，体力上限+1",
						weight: 5,
						cost: 150,
						action(target) {
							game.setGameInfo("huanhundan", get.gameInfo(1) + 1)
							target.gainMaxHp();
						}
					},
					{
						text: "获得还魂丹一个",
						weight: 2,
						cost: 50,
						action(target) {
							game.setGameInfo("huanhundan", get.gameInfo(1) + 1)
						}
					},
					{
						text: "体力上限+1",
						weight: 5,
						cost: 100,
						action(target) {
							target.gainMaxHp();
						}
					},
					{
						text: "向当前牌堆中添加六根【如意金箍棒】",
						weight: 4,
						action(target) {
							let cards = [];
							for (let i = 2; i < 8; i++) {
								cards.push(game.createCard2("ruyijingubang", i % 2 ? "club" : "spade", i));
							}
							game.broadcastAll(() => lib.inpile.add("ruyijingubang"));
							game.cardsGotoPile(cards, () => ui.cardPile.childNodes[get.rand(0, ui.cardPile.childNodes.length - 1)]);
						}
					},
					{
						text: "向当前牌堆中添加各个花色的8点【毒】各五张",
						weight: 4,
						gain: 70,
						action(target) {
							var cds = [];
							for (var i of lib.suit) {
								for (var j = 0; j < 5; j++) {
									cds.push(game.createCard2("du", i, 8));
								}
							}
							game.broadcastAll(function () {
								lib.inpile.add("du");
							});
							game.cardsGotoPile(cds, () => {
								return ui.cardPile.childNodes[get.rand(0, ui.cardPile.childNodes.length - 1)];
							});
						}
					},
					{
						text: "向当前牌堆中添加随机点数的♥血【杀】5张",
						weight: 4,
						gain: 20,
						action(target) {
							var cds = [];
							for (var j = 0; j < 5; j++) {
								cds.push(game.createCard2("sha", "heart", Math.floor(Math.random() * 13) + 1, "sw_xue"));
							}
							game.cardsGotoPile(cds, () => {
								return ui.cardPile.childNodes[get.rand(0, ui.cardPile.childNodes.length - 1)];
							});
						}
					},
					{
						text: "向当前牌堆中添加随机点数的♠【海神三叉戟】3张",
						weight: 4,
						gain: 20,
						action(target) {
							var cds = [];
							for (var j = 0; j < 3; j++) {
								cds.push(game.createCard2("sw_haishensanchaji", "spade", Math.floor(Math.random() * 13) + 1));
							}
							game.cardsGotoPile(cds, () => {
								return ui.cardPile.childNodes[get.rand(0, ui.cardPile.childNodes.length - 1)];
							});
						}
					},
					{
						text: "复原武将牌并恢复所有废弃的装备栏",
						weight: 2,
						action(target) {
							target.link(false);
							target.turnOver(false);
							var list = [];
							for (var i = 1; i <= 5; i++) {
								for (var j = 0; j < target.countDisabledSlot(i); j++) {
									list.push("equip" + i);
								}
							}
							target.enableEquip(list);
						}
					},
					{
						text: "在下一关中获得技能【回生】",
						weight: 3,
						action(target) {
							target.addSkill("sw_huisheng");
							target.restoreSkill("sw_huisheng");
						}
					},
					{
						text: "获得50金币",
						weight: 3,
						gain: 50,
						action(target) {

						}
					},
					{
						text: "获得【白银钥匙】×1",
						weight: 5,
						cost: 100,
						action(target) {
							target.addItem("sw_key_silver")
						}
					},
					{
						text: "获得【黄金钥匙】×1",
						weight: 5,
						cost: 200,
						action(target) {
							target.addItem("sw_key_gold")
						}
					},
					{
						text: "获得【钻石钥匙】×1",
						weight: 5,
						cost: 400,
						action(target) {
							target.addItem("sw_key_diamond")
						}
					},
					// {
					// 	text: "在下一关中获得技能【魔法】",
					// 	weight: 1,
					// 	action(target) {
					// 		target.addSkill("mofaLDW");
					// 		target.setMark("mofaLDW_used", 0);
					// 		target.setMark("mofaLDW_gainCount", 0);
					// 	}
					// },
					//待更新更多奖励项
				];
				//获取指定数量的奖励，考虑权重
				function getWeightedRandomRewards(player, count) {
					let result = [];
					let money = player.getMoney()
					let candidates = rewards.slice().filter(r => money >= (r.cost ? r.cost : 0)); //原始奖励列表
					while (result.length < count && candidates.length) {
						//构建权重池
						let pool = [];
						for (let item of candidates) {
							for (let i = 0; i < item.weight; i++) {
								pool.push(item);
							}
						}
						if (pool.length == 0) break;

						//抽一个
						let choice = pool[Math.floor(Math.random() * pool.length)];

						result.push(choice);
						//从候选中移除，确保唯一
						candidates = candidates.filter(r => r !== choice);
					}
					return result;
				}
				//奖励逻辑
				while (targets.length) {
					let target = targets.shift();
					game.changeState(target, "选择奖励")
					const rewardList = getWeightedRandomRewards(target, 4);
					const result = await target.chooseControl()
						.set("choiceList", rewardList.map(r => {
							let str = r.text
							if(r.cost) str += `(消耗：${r.cost}金币)`
							if(r.gain) str += `(获得：${r.gain}金币)`
							return str
						}))
						.set("prompt", "请选择一项奖励")
						.forResult();
					var selected = rewardList[result.index];
					if(selected.gain) target.addInfo("money", selected.gain)
					if(selected.cost) target.removeInfo("money", selected.cost)
					game.log(target, "选择了", "#y" + selected.text);
					game.changeState(target, "选择奖励", true)
					selected.action(target);
				}
			},
			chooseReward: async function(event) {
				const player = event.player || game.me
				var rewards = event.rewards || [
					{
						text: "回复1点体力并摸一张牌",
						weight: 1,
						action(target) {
							target.recover();
							target.draw();
						}
					},
				];
				//获取指定数量的奖励，考虑权重
				function getWeightedRandomRewards(count) {
					let result = [];
					let candidates = rewards.slice(); //原始奖励列表
					while (result.length < count && candidates.length) {
						//构建权重池
						let pool = [];
						for (let item of candidates) {
							for (let i = 0; i < item.weight; i++) {
								pool.push(item);
							}
						}
						if (pool.length == 0) break;

						//抽一个
						let choice = pool[Math.floor(Math.random() * pool.length)];

						result.push(choice);
						//从候选中移除，确保唯一
						candidates = candidates.filter(r => r !== choice);
					}
					return result;
				}
				//奖励逻辑
				game.changeState(player, "选择奖励")
				const rewardList = getWeightedRandomRewards(Math.min(3, rewards.length));
				const result = await player.chooseControl()
					.set("choiceList", rewardList.map(r => r.text))
					.set("prompt", "请选择一项奖励")
					.forResult();
				var selected = rewardList[result.index];
				game.log(player, "选择了", "#y" + selected.text);
				game.changeState(player, "选择奖励", true)
				selected.action(player);
			},
		},
	},
	ai: {

	},
	ui: {
		create: {
			bagButton() {
				// 创建按钮
				let backpackButton = ui.create.div(".backpackButton", ui.arena);
				backpackButton.innerHTML = "🎒背包";

				Object.assign(backpackButton.style, {
					position: "absolute",
					top: "60%",
					right: "1%",
					transform: "translateY(-50%)",
					padding: "10px 20px",
					background: "rgba(0, 0, 0, 0.6)",
					color: "white",
					borderRadius: "8px",
					cursor: "pointer",
					zIndex: 4,
					transition: "all 0.1s ease",
					userSelect: "none",
				});
				backpackButton.addEventListener(lib.config.touchscreen ? "touchstart" : "mousedown", () => {
					backpackButton.style.transform = "translateY(-50%) scale(0.95)";
					backpackButton.style.background = "rgba(0, 0, 0, 0.8)";
				});
				backpackButton.addEventListener(lib.config.touchscreen ? "touchend" : "mouseup", () => {
					backpackButton.style.transform = "translateY(-50%) scale(1)";
					backpackButton.style.background = "rgba(0, 0, 0, 0.6)";
				});
				// backpackButton.addEventListener("mouseleave", () => {
				// 	backpackButton.style.transform = "translateY(-50%) scale(1)";
				// 	backpackButton.style.background = "rgba(0, 0, 0, 0.6)";
				// });
				backpackButton.addEventListener("click", function () {
					game.openBag()
				});
				return backpackButton
			}
		},
	},
	get: {
		//attitude: function (from, to) {
		//	if (from.boss === to.boss) return 10;
		//	return -10;
		//},
		gameInfo: function (name = undefined) {
			if (typeof name === "string") return _status.gameInfomation[name]
			else if (typeof name === "number") {
				const list = [_status.gameInfomation.killNum, _status.gameInfomation.huanhundan, _status.gameInfomation.version, _status.gameInfomation.newversion]
				if (name < list.length) return list[name]
				else return undefined
			}
			return _status.gameInfomation
		},
		chestList: function () {
			return ["sw_silverchest", "sw_goldchest", "sw_diamondchest", "sw_ironchest", "sw_legendchest"]
		},
		rawAttitude: function (from, to) {
				var x = 0,
					num = 0,
					temp,
					i;
				if (_status.ai.customAttitude) {
					for (i = 0; i < _status.ai.customAttitude.length; i++) {
						temp = _status.ai.customAttitude[i](from, to);
						if (temp != undefined) {
							x += temp;
							num++;
						}
					}
				}
				if (num) {
					return x / num;
				}
				if (_status.mode == "purple") {
					var real = get.realAttitude(from, to);
					if (from == to || to.identityShown || (from.storage.zhibi && from.storage.zhibi.includes(to)) || (_status.yeconfirm && ["rYe", "bYe"].includes(to.identity) && ["rYe", "bYe"].includes(to.identity))) return real * 1.1;
					return (to.ai.shown + 0.1) * real + (from.identity.slice(0, 1) == to.identity.slice(0, 1) ? 3 : -3) * (1 - to.ai.shown);
				} else if (_status.mode == "stratagem") {
					var x = 0,
						num = 0,
						temp,
						i;
					if (_status.ai.customAttitude) {
						for (i = 0; i < _status.ai.customAttitude.length; i++) {
							temp = _status.ai.customAttitude[i](from, to);
							if (temp != undefined) {
								x += temp;
								num++;
							}
						}
					}
					if (num) {
						return x / num;
					}
					var real = get.realAttitude(from, to),
						zhibi = from.storage.zhibi,
						stratagem_expose = from.storage.stratagem_expose,
						followCamouflage = true;
					if (to.ai.shown) return to.ai.shown * (real + (from.identity == to.identity || (from.identity == "zhu" && to.identity == "zhong") || (from.identity == "zhong" && to.identity == "zhu") || (from.identity == "nei" && to.identity == "zhu" && get.situation() <= 1) || (to.identity == "nei" && get.situation() <= 0 && ["zhu", "zhong"].includes(from.identity)) || (get.situation() >= 3 && from.identity == "fan") ? 2.9 : -2.9));
					if (from == to || to.identityShown || (((stratagem_expose && stratagem_expose.includes(to)) || (zhibi && zhibi.includes(to))) && !to.ai.stratagemCamouflage)) return real * 1.1;
					if (from.identity == "nei" && to.ai.stratagemCamouflage) return real * 1.1;
					if (to.identity == "nei") {
						if (from.identity == "fan") {
							if (get.population("zhong") == 0) {
								if (zhibi) {
									var dead = game.dead.slice();
									for (var current of dead) {
										if (from.storage.zhibi.includes(current) && current.ai.stratagemCamouflage) {
											if (from.storage.stratagem_expose && from.storage.stratagem_expose.includes(to)) return -7;
										}
									}
									if (zhibi.includes(to)) return 3;
								}
							}
						}
					}
					if (
						to.identity == "fan" &&
						from.identity == "nei" &&
						zhibi.includes(game.zhu) &&
						game.players
							.filter(i => i != from && !zhibi.includes(i))
							.map(i => i.identity)
							.reduce((p, c) => (!p.includes(c) ? p.push(c) && p : p), []).length == 1
					)
						return real;
					for (var fan of game.dead) {
						if (fan.identity != "fan" || !fan.storage.stratagem_revitalization) continue;
						for (var current of fan.storage.stratagem_expose) {
							if (to == current) {
								return real;
							}
						}
					}
					if (from.identity == "fan" && to.identity == "fan") {
						if (from.ai.stratagemCamouflage) {
							var zhu = game.zhu && game.zhu.isZhu && game.zhu.identityShown ? game.zhu : undefined;
							if (zhu) {
								if (zhu.storage.stratagem_expose && zhu.storage.stratagem_expose.includes(to)) return 0;
							}
							if (zhibi && zhibi.includes(to)) return -7;
						}
						if (to.ai.stratagemCamouflage) {
							var zhu = game.zhu && game.zhu.isZhu && game.zhu.identityShown ? game.zhu : undefined;
							if (zhu) {
								if (zhu.storage.stratagem_expose && zhu.storage.stratagem_expose.includes(to)) return 0;
							}
							if (zhibi && zhibi.includes(to)) return -7;
						}
					}
					if (from.identity != "nei" && zhibi && zhibi.includes(to) && !to.identityShown && followCamouflage && to.ai.stratagemCamouflage) return -5;
					if (from.identity != "nei" && stratagem_expose && stratagem_expose.includes(to) && !to.identityShown) return -5;
					if (zhibi) {
						for (var to2 of zhibi) {
							if (to2.storage.stratagem_expose) {
								if (to2.ai.stratagemCamouflage) {
									for (var to3 of to2.storage.stratagem_expose) {
										if (zhibi.slice().addArray(stratagem_expose).includes(to3)) {
											if (to == to2) {
												return real;
											}
										} else if (to == to3) {
											return Math.abs(real + 10) / 10;
										}
									}
								} else {
									for (var to3 of to2.storage.stratagem_expose) {
										if (!zhibi.slice().addArray(stratagem_expose).includes(to3) && to == to3) {
											return get.rawAttitude(to3, to) * Math.sign(real);
										}
									}
								}
							}
						}
					}
					return Math.max(-1, Math.min(-0.1, (-Math.min(5, to.countCards("hes") / 2 + 1) / 5 - Math.max(0, 5 - to.hp) / 4) / 2));
				}
				//正常身份模式态度
				var difficulty = 0;
				if (to == game.me) difficulty = 2 - get.difficulty();
				if (from == to || to.identityShown || from.storage.dongcha == to || to.identityShown || (from.storage.zhibi && from.storage.zhibi.includes(to))) {
					return get.realAttitude(from, to) + difficulty * 1.5;
				} else {
					if (from.identity == "zhong" && to.ai.shown == 0 && from.ai.tempIgnore && !from.ai.tempIgnore.includes(to)) {
						for (var i = 0; i < game.players.length; i++) {
							if (game.players[i].ai.shown == 0 && game.players[i].identity == "fan") {
								return -0.1 + difficulty * 1.5;
							}
						}
					}
					var aishown = to.ai.shown;
					if ((to.identity == "nei" || to.identity == "commoner") && to.ai.shown < 1 && (to.ai.identity_mark == "fan" || to.ai.identity_mark == "zhong")) {
						aishown = 0.5;
					} else if (aishown == 0 && to.identity != "fan" && to.identity != "zhu") {
						var fanshown = true;
						for (var i = 0; i < game.players.length; i++) {
							if (game.players[i].identity == "fan" && game.players[i].ai.shown == 0 && game.players[i] != from) {
								fanshown = false;
								break;
							}
						}
						if (fanshown) aishown = 0.3;
					}
					return get.realAttitude(from, to) * aishown + difficulty * 1.5;
				}
			},
		realAttitude: function (from, to) {
			if (_status.mode == "purple") {
				if (["rZhu", "rZhong", "bNei"].includes(from.identity)) {
					if (to.identity == "rZhu") return 8;
					if (["rZhong", "bNei"].includes(to.identity)) return 7;
					return -7;
				} else if (["bZhu", "bZhong", "rNei"].includes(from.identity)) {
					if (to.identity == "bZhu") return 8;
					if (["bZhong", "rNei"].includes(to.identity)) return 7;
					return -7;
				} else {
					if (["rYe", "bYe"].includes(to.identity)) return 7;
					if (
						["rZhu", "bZhu"].includes(to.identity) &&
						game.hasPlayer(function (current) {
							return ["rZhong", "bZhong", "rNei", "bNei"].includes(current.identity);
						})
					)
						return 6.5;
					return -7;
				}
			} else if (_status.mode == "stratagem") {
				if (!game.zhu) {
					if (from.identity == "nei" || to.identity == "nei") return -1;
					if (from.identity == to.identity) return 6;
					return -6;
				}
				var situation = get.situation();
				var identity = from.identity;
				var identity2 = to.identity;
				if (identity2 == "zhu" && !to.isZhu) {
					identity2 = "zhong";
					if (from == to) return 10;
				}
				if (from != to && to.identity == "nei" && to.ai.shown < 1 && (to.ai.identity_mark == "fan" || to.ai.identity_mark == "zhong")) {
					identity2 = to.ai.identity_mark;
				}
				if (from.identity != "nei" && from != to && get.population("fan") == 0 && identity2 == "zhong") {
					for (var i = 0; i < game.players.length; i++) {
						if (game.players[i].identity == "nei" && game.players[i].ai.identity_mark == "zhong" && game.players[i].ai.shown < 1) {
							identity2 = "nei";
							break;
						}
					}
				}
				switch (identity) {
					case "zhu":
						switch (identity2) {
							case "zhu":
								return 10;
							case "zhong":
								return 6;
							case "nei":
								if (game.players.length == 2) return -10;
								if (to.identity == "zhong") return 0;
								if (get.population("fan") == 0) {
									if (to.ai.identity_mark == "zhong" && to.ai.shown < 1) return 0;
									return -1;
								}
								if (get.population("fan") == 1 && get.population("nei") == 1 && game.players.length == 3) {
									var fan;
									for (var i = 0; i < game.players.length; i++) {
										if (game.players[i].identity == "fan") {
											fan = game.players[i];
											break;
										}
									}
									if (fan) {
										if (to.hp > 1 && to.hp > fan.hp && to.countCards("he") > fan.countCards("he")) {
											return -3;
										}
									}
									return 0;
								}
								if (situation > 1) return Math.max((situation - 8) / 3, -2);
								return Math.min(3, get.population("fan"));
							case "fan":
								if (get.population("fan") == 1 && get.population("nei") == 1 && game.players.length == 3) {
									var nei;
									for (var i = 0; i < game.players.length; i++) {
										if (game.players[i].identity == "nei") {
											nei = game.players[i];
											break;
										}
									}
									if (nei) {
										if (nei.hp > 1 && nei.hp > to.hp && nei.countCards("he") > to.countCards("he")) {
											return 0;
										}
									}
									return -3;
								}
								return -4;
						}
						break;
					case "zhong":
						switch (identity2) {
							case "zhu":
								return 10;
							case "zhong":
								if (from == to) return 5;
								if (get.population("zhong") > 1) return 3;
								return 4;
							case "nei":
								if (get.population("fan") == 0 && get.population("zhong") == 1) return -2;
								if (get.population("zhong") >= 1) return Math.min(3, -situation);
								return 3;
							case "fan":
								return -8;
						}
						break;
					case "nei":
						if (identity2 == "zhu" && game.players.length == 2) return -10;
						if (from != to && identity2 != "zhu" && game.players.length == 3) return -8;
						var strategy = get.aiStrategy();
						if (strategy == 4) {
							if (from == to) return 10;
							return 0;
						}
						var num;
						switch (identity2) {
							case "zhu":
								if (strategy == 6) return -1;
								if (strategy == 5) return 10;
								if (to.hp <= 0) return 10;
								if (get.population("fan") == 1) {
									var fan;
									for (var i = 0; i < game.players.length; i++) {
										if (game.players[i].identity == "fan") {
											fan = game.players[i];
											break;
										}
									}
									if (fan) {
										if (to.hp > 1 && to.hp > fan.hp && to.countCards("he") > fan.countCards("he")) {
											return -3;
										}
									}
									return 0;
								} else {
									if (situation > 1 || get.population("fan") == 0) num = 0;
									else num = get.population("fan") + Math.max(0, 3 - game.zhu.hp);
								}
								if (strategy == 2) num--;
								if (strategy == 3) num++;
								return num;
							case "zhong":
								if (strategy == 5) return Math.min(0, -situation);
								if (strategy == 6) return Math.max(-1, -situation);
								if (get.population("fan") == 0) num = -5;
								else if (situation <= 0) num = 0;
								else if (game.zhu && game.zhu.hp < 2) num = 0;
								else if (game.zhu && game.zhu.hp == 2) num = -1;
								else if (game.zhu && game.zhu.hp <= 2 && situation > 1) num = -1;
								else num = -2;
								if (strategy == 2) num--;
								if (strategy == 3) num++;
								return num;
							case "nei":
								if (from == to) return 10;
								if (from.ai.friend.includes(to)) return 5;
								if (get.population("fan") + get.population("zhong") > 0) return 0;
								return -5;
							case "fan":
								if (strategy == 5) return Math.max(-1, situation);
								if (strategy == 6) return Math.min(0, situation);
								if ((game.zhu && game.zhu.hp <= 2 && situation < 0) || situation < -1) num = -3;
								else if (situation < 0 || get.population("zhong") == 0) num = -2;
								else if ((game.zhu && game.zhu.hp >= 4 && situation > 0) || situation > 1) num = 1;
								else num = 0;
								if (strategy == 2) num++;
								if (strategy == 3) num--;
								return num;
						}
						break;
					case "fan":
						switch (identity2) {
							case "zhu":
								if (get.population("nei") > 0) {
									if (situation == 1) return -6;
									if (situation > 1) return -5;
								}
								return -8;
							case "zhong":
								if (game.zhu.hp >= 3 && to.hp == 1) {
									return -10;
								}
								return -7;
							case "nei":
								if (get.population("fan") == 1) return 0;
								if (get.population("zhong") == 0) return -2;
								if (game.zhu && game.zhu.hp <= 2 && game.zhu.identityShown) return -1;
								return 3;
							case "fan":
								return 5;
						}
				}
			}
			//正常身份模式态度
			if (!game.zhu) {
				if (from.identity == "nei" || to.identity == "nei" || from.identity == "commoner" || to.identity == "commoner") return -1;
				if (from.identity == to.identity) return 6;
				return -6;
			}
			var situation = get.situation();
			var identity = from.identity;
			var identity2 = to.identity;
			if (identity2 == "zhu" && !to.isZhu) {
				identity2 = "zhong";
				if (from == to) return 10;
			}
			if (from != to && to.identity == "nei" && to.ai.shown < 1 && (to.ai.identity_mark == "fan" || to.ai.identity_mark == "zhong")) {
				identity2 = to.ai.identity_mark;
			}
			if (from.identity != "nei" && from.identity != "commoner" && from != to && get.population("fan") == 0 && identity2 == "zhong") {
				for (var i = 0; i < game.players.length; i++) {
					if (game.players[i].identity == "nei" && game.players[i].ai.identity_mark == "zhong" && game.players[i].ai.shown < 1) {
						identity2 = "nei";
						break;
					} else if (game.players[i].identity == "commoner" && game.players[i].ai.identity_mark == "zhong" && game.players[i].ai.shown < 1) {
						identity2 = "commoner";
						break;
					}
				}
			}
			var zhongmode = false;
			if (!game.zhu.isZhu) {
				zhongmode = true;
			}
			switch (identity) {
				case "zhu":
					switch (identity2) {
						case "zhu":
							return 10;
						case "zhong":
						case "mingzhong":
							return 6;
						case "nei":
							if (game.players.length == 2) return -10;
							if (to.identity == "zhong") return 0;
							if (get.population("fan") == 0) {
								if (to.ai.identity_mark == "zhong" && to.ai.shown < 1) return 0;
								return -0.5;
							}
							if (zhongmode && to.ai.sizhong && to.ai.shown < 1) return 6;
							if (get.population("fan") == 1 && get.population("nei") == 1 && game.players.length == 3) {
								var fan;
								for (var i = 0; i < game.players.length; i++) {
									if (game.players[i].identity == "fan") {
										fan = game.players[i];
										break;
									}
								}
								if (fan) {
									if (to.hp > 1 && to.hp > fan.hp && to.countCards("he") > fan.countCards("he")) {
										return -3;
									}
								}
								return 0;
							}
							if (situation > 1) return 0;
							return Math.min(3, get.population("fan"));
						case "fan":
							if (get.population("fan") == 1 && get.population("nei") == 1 && game.players.length == 3) {
								var nei;
								for (var i = 0; i < game.players.length; i++) {
									if (game.players[i].identity == "nei") {
										nei = game.players[i];
										break;
									}
								}
								if (nei) {
									if (nei.hp > 1 && nei.hp > to.hp && nei.countCards("he") > to.countCards("he")) {
										return 0;
									}
								}
								return -3;
							}
							return -4;
						case "commoner":
							if (to.identity == "zhong") return 0;
							if (get.population("fan") == 0) {
								if (to.ai.identity_mark == "zhong" && to.ai.shown < 1) return 0;
								return -0.5;
							}
							if (zhongmode && to.ai.sizhong && to.ai.shown < 1) return 6;
							if (game.players.length == 3) {
								var fan;
								for (var i = 0; i < game.players.length; i++) {
									if (game.players[i].identity == "fan") {
										fan = game.players[i];
										break;
									}
								}
								if (fan) {
									if (to.hp > 1 && to.hp > fan.hp && to.countCards("he") > fan.countCards("he")) {
										return -3;
									}
								}
								return 3;
							}
							if (situation < 0 && game.zhu && game.zhu.hp <= 2) return -3.8;
							return Math.max(-4, 2 - get.population("fan"));
					}
					break;
				case "zhong":
				case "mingzhong":
					switch (identity2) {
						case "zhu":
							return 10;
						case "zhong":
						case "mingzhong":
							return 4;
						case "nei":
							if (get.population("fan") == 0) return -2;
							if (zhongmode && to.ai.sizhong && to.ai.shown < 1) return 6;
							return Math.min(3, -situation);
						case "fan":
							return -8;
						case "commoner":
							return Math.min(3, Math.max(-3, situation - 0.2));
					}
					break;
				case "nei":
					if (identity2 == "zhu" && game.players.length == 2) return -10;
					if (from != to && identity2 != "zhu" && identity2 != "commoner" && game.players.length == 3) return -8;
					var strategy = get.aiStrategy();
					if (strategy == 4) {
						if (from == to) return 10;
						return 0;
					}
					var num;
					switch (identity2) {
						case "zhu":
							if (strategy == 6) return -1;
							if (strategy == 5) return 10;
							if (to.hp <= 0) return 10;
							if (get.population("fan") == 1) {
								var fan;
								for (var i = 0; i < game.players.length; i++) {
									if (game.players[i].identity == "fan") {
										fan = game.players[i];
										break;
									}
								}
								if (fan) {
									if (to.hp > 1 && to.hp > fan.hp && to.countCards("he") > fan.countCards("he")) {
										return -1.7;
									}
								}
								return 0;
							} else {
								if (situation > 1 || get.population("fan") == 0) num = 0;
								else num = get.population("fan") + Math.max(0, 3 - game.zhu.hp);
							}
							if (strategy == 2) num--;
							if (strategy == 3) num++;
							return num;
						case "zhong":
							if (strategy == 5) return Math.min(0, -situation);
							if (strategy == 6) return Math.max(-1, -situation);
							if (get.population("fan") == 0) num = -5;
							else if (situation <= 0) num = 0;
							else if (game.zhu && game.zhu.hp < 2) num = 0;
							else if (game.zhu && game.zhu.hp == 2) num = -1;
							else if (game.zhu && game.zhu.hp <= 2 && situation > 1) num = -1;
							else num = -2;
							if (zhongmode && situation < 2) {
								num = 4;
							}
							if (strategy == 2) num--;
							if (strategy == 3) num++;
							return num;
						case "mingzhong":
							if (zhongmode) {
								if (from.ai.sizhong == undefined) {
									from.ai.sizhong = Math.random() < 0.5;
								}
								if (from.ai.sizhong) return 6;
							}
							if (strategy == 5) return Math.min(0, -situation);
							if (strategy == 6) return Math.max(-1, -situation);
							if (get.population("fan") == 0) num = -5;
							else if (situation <= 0) num = 0;
							else num = -3;
							if (strategy == 2) num--;
							if (strategy == 3) num++;
							return num;
						case "nei":
							if (from == to) return 10;
							if (from.ai.friend.includes(to)) return 5;
							if (get.population("fan") + get.population("zhong") > 0) return 0;
							return -5;
						case "fan":
							if (strategy == 5) return Math.max(-1, situation);
							if (strategy == 6) return Math.min(0, situation);
							if ((game.zhu && game.zhu.hp <= 2 && situation < 0) || situation < -1) num = -3;
							else if (situation < 0 || get.population("zhong") + get.population("mingzhong") == 0) num = -2;
							else if ((game.zhu && game.zhu.hp >= 4 && situation > 0) || situation > 1) num = 1;
							else num = 0;
							if (strategy == 2) num++;
							if (strategy == 3) num--;
							return num;
						case "commoner":
							if (game.players.length <= 4) return 5;
							return Math.min(Math.max(-situation, -2), 2);
					}
					break;
				case "fan":
					switch (identity2) {
						case "zhu":
							if (get.population("nei") > 0) {
								if (situation == 1) return -6;
								if (situation > 1) return -5;
							}
							return -8;
						case "zhong":
							if (!zhongmode && game.zhu.hp >= 3 && to.hp == 1) {
								return -10;
							}
							return -7;
						case "mingzhong":
							return -5;
						case "nei":
							if (zhongmode && to.ai.sizhong) return -7;
							if (get.population("fan") == 1) return 0;
							if (get.population("zhong") + get.population("mingzhong") == 0) return -7;
							if (game.zhu && game.zhu.hp <= 2) return -1;
							return Math.min(3, situation);
						case "fan":
							return 5;
						case "commoner":
							return 2 * get.population("fan") - 3;
					}
					break;
				case "commoner":
					switch (identity2) {
						case "zhu":
							if (situation > 0) return 2 * Math.min(4, to.hp + to.countCards("h") / 4 - 2);
							if (situation >= -3 && game.zhu) return to.hp - 2 + to.countCards("h") / 4; //return Math.min(-0.1,5-game.zhu.hp);
							return to.hp + to.countCards("h") / 3 - 4;
						case "zhong":
							if (situation > 0) {
								if (to.hp >= 2) return Math.min(3, Math.max(1, to.hp + to.countCards("h") / 4 - 4));
								else return 0;
							}
							return -2;
						case "nei":
							if (game.players.length == 3 && get.population("nei") == 1) return Math.min(3.5, to.hp - 1.5 + to.countCards("h") / 3) - (to.hp < (game.zhu ? game.zhu.hp : 0) ? 4 : 0);
							if (game.players.length <= 4 && get.population("nei") == 1) return Math.min(5, to.hp - 1.5 + to.countCards("h") / 3);
							if (situation > 0) return -3;
							return 0;
						case "fan":
							if (situation < 0) return to.hp + to.countCards("h") / 4 - 1.7 * get.population("fan") + 2;
							else if (situation == 0) return 0;
							return 0.55 * get.population("fan") - 2.1;
						case "commoner":
							return from == to ? 10 : to.hp <= 2 ? -2 : 0;
					}
					break;
			}
		},
		situation: function (absolute) {
			var i, j, player;
			var zhuzhong = 0,
				total = 0,
				zhu,
				fan = 0;
			for (i = 0; i < game.players.length; i++) {
				player = game.players[i];
				var php = player.hp;
				if (player.hasSkill("benghuai") && php > 4) {
					php = 4;
				} else if (php > 6) {
					php = 6;
				}
				j = player.countCards("h") + player.countCards("e") * 1.5 + php * 2;
				if (player.identity == "zhu") {
					zhuzhong += j * 1.2 + 5;
					total += j * 1.2 + 5;
					zhu = j;
				} else if (player.identity == "zhong" || player.identity == "mingzhong") {
					zhuzhong += j * 0.8 + 3;
					total += j * 0.8 + 3;
				} else if (player.identity == "fan") {
					zhuzhong -= j + 4;
					total += j + 4;
					fan += j + 4;
				}
			}
			if (absolute) return zhuzhong;
			var result = parseInt(10 * Math.abs(zhuzhong / total));
			if (zhuzhong < 0) result = -result;
			if (!game.zhong) {
				if (zhu < 12 && fan > 30) result--;
				if (zhu < 6 && fan > 15) result--;
				if (zhu < 4) result--;
			}
			return result;
		},
		insightResult: function (from, to) {
			var friend = "friend",
				enemy = "enemy";
			if (from.identity == "nei") return to.identity;
			if (to.identity == "nei") return friend;
			if (from.ai.stratagemCamouflage || to.ai.stratagemCamouflage) return enemy;
			if (from.identity == to.identity || (from.identity == "zhu" && to.identity == "zhong") || (from.identity == "zhong" && to.identity == "zhu")) return friend;
			return enemy;
		},
	},
	character: MAIN.character,
	skill: MAIN.skill,
	translate: MAIN.translate,
	dynamicTranslate: MAIN.dynamicTranslate,
	card: MAIN.card,
	characterTitle: MAIN.characterTitle,
	help: {

	},
};

export default () => {
	return hemengaozhan
}
